import React, { useState, useEffect } from 'react'
import {
	Space,
	Table,
	Button,
	Form,
	Input,
	InputNumber,
	Modal,
	Tag,
	Switch,
	Popover,
	notification,
	message
} from 'antd'
import {
	DeleteOutlined,
	EditOutlined,
	ExclamationCircleOutlined
} from '@ant-design/icons'
import "./index.css"
import { getRights } from '../../../utils/request/get'
import { useSelector } from 'react-redux'
import { deleteChildrenById, deleteRightById } from '../../../utils/request/delete'
import { updateRightById, changeRightPermission } from '../../../utils/request/put'

const { confirm } = Modal

export default function RightList() {
	const token = useSelector(state => state.TokenReducer.token)
	const [dataSource, setDataSource] = useState([])
	const [editingKey, setEditingKey] = useState('')
	const [form] = Form.useForm()
	const [checkStrictly] = useState(false)
	useEffect(() => {
		async function fetchData() {
			if (token) {
				const res = await getRights(token.roleId)
				let list = []
				res.forEach(item => {
					if (item.grade === 1) {
						list.push(item)
					}
					if (item.children.length === 0) {
						item.children = ''
					}
				})
				setDataSource(list)
			}
		}
		fetchData()
	}, [token])

	const isEditing = (record) => record.key === editingKey
	const changePermission = async (item) => {
		item.pagePermission = item.pagePermission === 1 ? 0 : 1
		// console.log(item);
		setDataSource([...dataSource])
		let res1 = null
		// let res2 = null
		res1 = await changeRightPermission(item.id, item.pagePermission)
		// 修改right下面所有pagePermission为1的children的权限
		// res2 = await changeChildrenPermissionBehindRight(item.id, item.pagePermission)
		// axios.patch(`/api/rights/${item.id}`, { pagePermission: item.pagePermission })
		if (res1) {
			// if (!res2) {
			// 	message.error('更新失败')
			// 	return
			// }
			message.success('更新成功')
		} else {
			message.error('更新失败')
		}
	}
	const deleteData = (item) => {
		if (item.grade === 1) {
			setDataSource(dataSource.filter(data => data.id !== item.id));
			deleteRightById(item.id)
			// axios.delete(`/api/rights/${item.id}`)
		} else {
			let list = dataSource.filter(data => data.id === item.rightId)
			list[0].children = list[0].children.filter(data => data.id !== item.id)
			setDataSource([...dataSource])
			deleteChildrenById(item.id)
			// axios.delete(`/api/children/${item.id}`)
		}
	}
	const showConfirm = (type, item) => {
		let obj = {
			icon: <ExclamationCircleOutlined />,
		}
		switch (type) {
			case 'CANCEL':
				obj.title = '您确定要取消吗?'
				obj.onOk = function () { setEditingKey(''); }
				obj.onCancel = function () { console.log('Cancel'); }
				break
			case 'DELETE':
				obj.title = '您确定要删除吗?'
				obj.cancelText = '取消'
				obj.okText = '确定'
				obj.onOk = function () { deleteData(item); }
				obj.onCancel = function () { console.log('Cancel'); }
				break
			default: break
		}
		confirm(obj)
	};
	const openNotification = (type, des) => {
		notification[type]({
			message: '更新通知',
			description: des,
			placement: 'bottomRight'
		})
	}
	const save = async (key) => {
		try {
			const row = await form.validateFields()
			const newData = [...dataSource]
			const index = newData.findIndex((item) => key === item.key)

			if (index > -1) {
				const item = newData[index]
				newData.splice(index, 1, { ...item, ...row }) // 用 row 这个对象 替换 item
				setDataSource(newData)
				updateRightById(item.id, row).then((res) => {
					console.log(res);
					if (res.status === 200) {
						openNotification('success', '修改成功！')
					}
				})
				setEditingKey('')
			} else {
				newData.push(row)
				setDataSource(newData)
				setEditingKey('')
			}
		} catch (err) {
			console.log('Validate Failed:', err)
		}
	}
	const EditableCell = ({
		editing,
		dataIndex,
		title,
		inputType,
		record,
		index,
		children,
		...restProps
	}) => {
		const inputNode = inputType === 'number' ? <InputNumber /> : <Input />
		return (
			<td {...restProps}>
				{editing ? (
					<Form.Item
						name={dataIndex}
						style={{
							margin: 0,
						}}
						rules={[
							{
								required: true,
								message: `请输入 ${title}!`,
							},
						]}
					>
						{inputNode}
					</Form.Item>
				) : (
					children
				)}
			</td>
		)
	}

	const columns = [
		{
			title: 'ID',
			dataIndex: 'id',
			key: 'id',
			editable: true,
			render: (id) => {
				return <b>{id}</b>
			}
		},
		{
			title: '权限名称',
			dataIndex: 'title',
			key: 'title',
			editable: true
		},
		{
			title: '权限路径',
			dataIndex: 'key',
			key: 'key',
			editable: true,
			render: (key) => {
				return <Tag color="orange">{key}</Tag>
			}
		},
		{
			title: '操作',
			dataIndex: '',
			key: 'x',
			render: (_, record) => {
				const editable = isEditing(record)
				return editable ? (
					<span>
						<Button
							onClick={() => save(record.key)}
							style={{ marginRight: 8 }}
							type="primary"
						>Save</Button>
						<Button onClick={() => showConfirm("CANCEL")}>Cancel</Button>
					</span>
				) : (
					<div>
						<Button
							danger disabled={editingKey !== ''} onClick={() => showConfirm("DELETE", record)} shape="circle" icon={<DeleteOutlined />}>
						</Button>&nbsp;&nbsp;
						<Popover
							content={
								<div style={{ textAlign: "center" }}>
									<Switch
										checked={record.pagePermission}
										onChange={() => changePermission(record)}></Switch>
								</div>
							}
							title="是否开启权限" trigger={record.grade !== 1 || record.key === '/right-manage' ? "" : "click"}>
							<Button
								disabled={record.grade !== 1 || record.key === '/right-manage'}
								shape="circle"
								icon={<EditOutlined />}
								type="primary"></Button>
							{/* <Button disabled={editingKey !== ''} onClick={() => edit(record)} shape="circle" icon={<EditOutlined />} type="primary"></Button> */}
						</Popover>
					</div>
				)
			}
		}
	]
	const mergedColumns = columns.map((col) => {
		// 若当前不可编辑
		if (!col.editable) {
			return col
		}

		// 可以编辑
		return {
			...col,
			onCell: (record) => ({
				record,
				inputType: col.dataIndex === 'age' ? 'number' : 'text',
				dataIndex: col.dataIndex,
				title: col.title,
				editing: isEditing(record)
			})
		}
	})
	const rowSelection = {
		onChange: (selectedRowKeys, selectedRows) => {
			console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows)
		},
		onSelect: (record, selected, selectedRows) => {
			console.log(record, selected, selectedRows)
		},
		onSelectAll: (selected, selectedRows, changeRows) => {
			console.log(selected, selectedRows, changeRows)
		},
	}

	return (
		<Form form={form} component={false}>
			<Space
				align="center"
				style={{
					marginBottom: 16,
				}}
			></Space>
			<Table
				components={{ body: { cell: EditableCell } }}
				bordered
				columns={mergedColumns}
				rowSelection={{ ...rowSelection, checkStrictly }}
				dataSource={dataSource}
				rowClassName="editable-row"
				pagination={{ pageSize: 5 }}
				rowKey={(item) => item.id}
			/>
		</Form>

	)
}